package com.tzf.msst.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tzf.msst.common.ErrorCode;
import com.tzf.msst.constant.CommonConstant;
import com.tzf.msst.exception.ThrowUtils;
import com.tzf.msst.mapper.UserCommentQstMapper;
import com.tzf.msst.model.dto.userCommentQst.UserCommentQstQueryRequest;
import com.tzf.msst.model.entity.UserCommentQst;
import com.tzf.msst.model.entity.User;
import com.tzf.msst.model.vo.UserCommentQstVO;
import com.tzf.msst.model.vo.UserVO;
import com.tzf.msst.service.UserCommentQstService;
import com.tzf.msst.service.UserService;
import com.tzf.msst.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户评论服务实现
 */
@Service
@Slf4j
public class UserCommentQstServiceImpl extends ServiceImpl<UserCommentQstMapper, UserCommentQst> implements UserCommentQstService {

    @Resource
    private UserService userService;

    /**
     * 校验数据
     *
     * @param userCommentQst
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validUserCommentQst(UserCommentQst userCommentQst, boolean add) {
        ThrowUtils.throwIf(userCommentQst == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        //String title = userCommentQst.getTitle();
        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            //ThrowUtils.throwIf(StringUtils.isBlank(title), ErrorCode.PARAMS_ERROR);
        }
        // 修改数据时，有参数则校验
        // todo 补充校验规则
        //if (StringUtils.isNotBlank(title)) {
        //    ThrowUtils.throwIf(title.length() > 80, ErrorCode.PARAMS_ERROR, "标题过长");
        //}
    }

    /**
     * 获取查询条件
     *
     * @param userCommentQstQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<UserCommentQst> getQueryWrapper(UserCommentQstQueryRequest userCommentQstQueryRequest) {
        QueryWrapper<UserCommentQst> queryWrapper = new QueryWrapper<>();
        if (userCommentQstQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = userCommentQstQueryRequest.getId();
        Long notId = userCommentQstQueryRequest.getNotId();
        String title = userCommentQstQueryRequest.getTitle();
        String content = userCommentQstQueryRequest.getContent();
        String searchText = userCommentQstQueryRequest.getSearchText();
        String sortField = userCommentQstQueryRequest.getSortField();
        String sortOrder = userCommentQstQueryRequest.getSortOrder();
        List<String> tagList = userCommentQstQueryRequest.getTags();
        Long userId = userCommentQstQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取用户评论封装
     *
     * @param userCommentQst
     * @param request
     * @return
     */
    @Override
    public UserCommentQstVO getUserCommentQstVO(UserCommentQst userCommentQst, HttpServletRequest request) {
        // 对象转封装类
        UserCommentQstVO userCommentQstVO = UserCommentQstVO.objToVo(userCommentQst);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = userCommentQst.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        userCommentQstVO.setUser(userVO);
        // 2. 已登录，获取用户点赞、收藏状态
        long userCommentQstId = userCommentQst.getId();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            // 获取点赞
            //QueryWrapper<UserCommentQstThumb> userCommentQstThumbQueryWrapper = new QueryWrapper<>();
            //userCommentQstThumbQueryWrapper.in("userCommentQstId", userCommentQstId);
            //userCommentQstThumbQueryWrapper.eq("userId", loginUser.getId());
            //UserCommentQstThumb userCommentQstThumb = userCommentQstThumbMapper.selectOne(userCommentQstThumbQueryWrapper);
            //userCommentQstVO.setHasThumb(userCommentQstThumb != null);
            //// 获取收藏
            //QueryWrapper<UserCommentQstFavour> userCommentQstFavourQueryWrapper = new QueryWrapper<>();
            //userCommentQstFavourQueryWrapper.in("userCommentQstId", userCommentQstId);
            //userCommentQstFavourQueryWrapper.eq("userId", loginUser.getId());
            //UserCommentQstFavour userCommentQstFavour = userCommentQstFavourMapper.selectOne(userCommentQstFavourQueryWrapper);
            //userCommentQstVO.setHasFavour(userCommentQstFavour != null);
        }
        // endregion

        return userCommentQstVO;
    }

    /**
     * 分页获取用户评论封装
     *
     * @param userCommentQstPage
     * @param request
     * @return
     */
    @Override
    public Page<UserCommentQstVO> getUserCommentQstVOPage(Page<UserCommentQst> userCommentQstPage, HttpServletRequest request) {
        List<UserCommentQst> userCommentQstList = userCommentQstPage.getRecords();
        Page<UserCommentQstVO> userCommentQstVOPage = new Page<>(userCommentQstPage.getCurrent(), userCommentQstPage.getSize(), userCommentQstPage.getTotal());
        if (CollUtil.isEmpty(userCommentQstList)) {
            return userCommentQstVOPage;
        }
        // 对象列表 => 封装对象列表
        List<UserCommentQstVO> userCommentQstVOList = userCommentQstList.stream().map(userCommentQst -> {
            return UserCommentQstVO.objToVo(userCommentQst);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = userCommentQstList.stream().map(UserCommentQst::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态
        Map<Long, Boolean> userCommentQstIdHasThumbMap = new HashMap<>();
        Map<Long, Boolean> userCommentQstIdHasFavourMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            Set<Long> userCommentQstIdSet = userCommentQstList.stream().map(UserCommentQst::getId).collect(Collectors.toSet());
            loginUser = userService.getLoginUser(request);
            // 获取点赞
            //QueryWrapper<UserCommentQstThumb> userCommentQstThumbQueryWrapper = new QueryWrapper<>();
            //userCommentQstThumbQueryWrapper.in("userCommentQstId", userCommentQstIdSet);
            //userCommentQstThumbQueryWrapper.eq("userId", loginUser.getId());
            //List<UserCommentQstThumb> userCommentQstUserCommentQstThumbList = userCommentQstThumbMapper.selectList(userCommentQstThumbQueryWrapper);
            //userCommentQstUserCommentQstThumbList.forEach(userCommentQstUserCommentQstThumb -> userCommentQstIdHasThumbMap.put(userCommentQstUserCommentQstThumb.getUserCommentQstId(), true));
            //// 获取收藏
            //QueryWrapper<UserCommentQstFavour> userCommentQstFavourQueryWrapper = new QueryWrapper<>();
            //userCommentQstFavourQueryWrapper.in("userCommentQstId", userCommentQstIdSet);
            //userCommentQstFavourQueryWrapper.eq("userId", loginUser.getId());
            //List<UserCommentQstFavour> userCommentQstFavourList = userCommentQstFavourMapper.selectList(userCommentQstFavourQueryWrapper);
            //userCommentQstFavourList.forEach(userCommentQstFavour -> userCommentQstIdHasFavourMap.put(userCommentQstFavour.getUserCommentQstId(), true));
        }
        // 填充信息
        userCommentQstVOList.forEach(userCommentQstVO -> {
            Long userId = userCommentQstVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            userCommentQstVO.setUser(userService.getUserVO(user));
            //userCommentQstVO.setHasThumb(userCommentQstIdHasThumbMap.getOrDefault(userCommentQstVO.getId(), false));
            //userCommentQstVO.setHasFavour(userCommentQstIdHasFavourMap.getOrDefault(userCommentQstVO.getId(), false));
        });
        // endregion

        userCommentQstVOPage.setRecords(userCommentQstVOList);
        return userCommentQstVOPage;
    }

}
